/*
 * @Author: 脉迈
 * @Date: 2021-09-14 16:33:20
 * @LastEditors: 脉迈
 * @LastEditTime: 2021-09-17 14:29:12
 */
import React, { useState } from "react";

/**
 * @description 编辑组件列表的上下文
 */
export const EditorContext = React.createContext<
  | {
      componentsList: any;
      activeIndex: number | null;
      handlerSetActiveIndex: Function;
      handlerSetComponentsList: Function;
    }
  | undefined
>(undefined);

EditorContext.displayName = "EditorContext";

/**
 * @description 定义provider 处理逻辑,暴露方法和属性
 */
export const EditorProvider = ({ children }: { children: React.ReactNode }) => {
  const [componentsList, setComponentsList] = useState<any>([]);
  const [activeIndex, setActiveIndex] = useState<number | null>(null);
  /**
   * @description   设置当前访问的索引
   * @param index   @type number
   */
  const handlerSetActiveIndex = (index: number) => {
    setActiveIndex(index);
  };
  /**
   * @description   当修改style后, 替换后，重新赋值
   * @param componentsList  @type any
   */
  const handlerSetComponentsList = (componentsList: any) => {
    setComponentsList(componentsList);
  };
  return (
    <EditorContext.Provider
      children={children}
      value={{
        componentsList,
        activeIndex,
        handlerSetActiveIndex,
        handlerSetComponentsList,
      }}
    />
  );
};

/**
 * 封装useEditorContext
 */

export const useEditorContext = () => {
  const context = React.useContext(EditorContext);
  if (!context) {
    throw new Error("请在EditorContext中使用");
  }
  return context;
};
